﻿using Prism.Events;
using Vision.Abstractions;
using Vision.Abstractions.Events;
using Vision.Abstractions.Processing;
using Vision.Processing;

namespace Vision.Host.Runtime
{
    /// <summary>
    /// 图像处理服务，监听原始图像总线，处理后通过EventAggregator发布
    /// </summary>
    public class ImageProcessingService
    {
        private readonly IImageBus _imageBus;
        private readonly IImageProcessor _imageProcessor;
        private readonly IImageProcessingParameters _parameters;
        private readonly IEventAggregator _eventAggregator;
        private readonly CancellationTokenSource _cancellationTokenSource;

        public ImageProcessingService(
            IImageBus imageBus,
            IImageProcessor imageProcessor,
            IImageProcessingParameters parameters,
            IEventAggregator eventAggregator)
        {
            _imageBus = imageBus;
            _imageProcessor = imageProcessor;
            _parameters = parameters;
            _eventAggregator = eventAggregator;
            _cancellationTokenSource = new CancellationTokenSource();

            // 启动处理任务
            _ = Task.Run(ProcessImagesAsync);
        }

        private async Task ProcessImagesAsync()
        {
            try
            {
                await foreach (var message in _imageBus.Reader.ReadAllAsync(_cancellationTokenSource.Token))
                {
                    if (message is CameraFrameMessage frame)
                    {

                        // 首先发布原图像
                        _eventAggregator.GetEvent<SourceImageEvent>().Publish(frame);

                        // 处理图像
                        var processedFrame = _imageProcessor.ProcessFrame(
                            frame,
                            _parameters.BinaryThreshold,
                            _parameters.EdgeThreshold);

                        // 通过EventAggregator发布处理后的图像
                        _eventAggregator.GetEvent<ProcessedImageEvent>().Publish(processedFrame);
                    }
                }
            }
            catch (OperationCanceledException)
            {
                // 正常取消，忽略
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"图像处理服务错误: {ex.Message}");
            }
        }

        public void Stop()
        {
            _cancellationTokenSource.Cancel();
        }
    }
}